package one.coder.jdk.daemonthread;

/**
 * 测试守护线程和普通线程区别。考虑应用场景
 * 
 * @author lihzh
 * @OneCoder-Blog http://www.coderli.com
 * @date 2012-6-21 下午4:20:35
 */
public class DaemonThreadMain {

	public static void main(String[] args) {
		// 测试两个用户线程
		twoCommonThread();
		// 测试一个用户一个守护线程
		oneCommonOneDaemonThread();
		// 测试两个守护线程
		twoDaemonThread();
	}
	
	/**
	 * 测试两个守护线程
	 * 
	 * @author lihzh(OneCoder)
	 * @date 2012-6-25 下午10:29:18
	 */
	private static void twoDaemonThread() {
		String princeOneName = "Prince One";
		Thread princeOne = new Thread(new MyRunner(5000, princeOneName), princeOneName);
		String princeTwoName = "Prince Two";
		Thread princeTwo = new Thread(new MyRunner(3000, princeTwoName), princeTwoName);
		princeOne.setDaemon(true);
		princeOne.start();
		System.out.println(princeOneName + "is starting.");
		princeTwo.setDaemon(true);
		princeTwo.start();
		System.out.println(princeTwoName + "is starting");
	}

	/**
	 * 测试一个用户一个守护线程
	 * 
	 * @author lihzh(OneCoder)
	 * @date 2012-6-25 下午10:22:58
	 */
	private static void oneCommonOneDaemonThread() {
		String girlName = "Girl";
		Thread girl = new Thread(new MyRunner(5000, girlName), girlName);
		String princeName = "Prince";
		Thread prince = new Thread(new MyRunner(3000, princeName), princeName);
		girl.start();
		System.out.println(girlName + "is starting.");
		prince.setDaemon(true);
		prince.start();
		System.out.println(prince + "is starting");
	}

	/**
	 * 测试两个用户线程的情况
	 * 
	 * @author lihzh(OneCoder)
	 * @date 2012-6-25 下午10:07:16
	 */
	private static void twoCommonThread() {
		String girlOneName = "Girl One";
		Thread girlOne = new Thread(new MyRunner(3000, girlOneName), girlOneName);
		String girlTwoName = "Girl Two";
		Thread girlTwo = new Thread(new MyRunner(5000, girlTwoName), girlTwoName);
		girlOne.start();
		System.out.println(girlOneName + "is starting.");
		girlTwo.start();
		System.out.println(girlTwoName + "is starting");
	}

	private static class MyRunner implements Runnable {
		
		private long sleepPeriod;
		private String threadName;
		
		public MyRunner(long sleepPeriod, String threadName) {
			this.sleepPeriod = sleepPeriod;
			this.threadName = threadName;
		}
		@Override
		public void run() {
			try {
				Thread.sleep(sleepPeriod);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(threadName + " has finished.");
		}
	}

}
